package delta;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamComparator {
	public static int DEFAULT_BUFFER_SIZE = 8192;
	private final int bufferSize_;

	InputStreamComparator() {
		this(DEFAULT_BUFFER_SIZE);
	}

	InputStreamComparator(int bufferSize) {
		bufferSize_ = bufferSize;
	}

	BufferedInputStream toBuffered(InputStream is) {
		if (is instanceof BufferedInputStream) {
			return (BufferedInputStream) is;
		} else {
			return new BufferedInputStream(is, bufferSize_);
		}
	}

	public int compare(InputStream ais, InputStream bis) throws IOException {
		ais = toBuffered(ais);
		bis = toBuffered(bis);
		for (;;) {
			int ar = ais.read();
			int br = bis.read();
			if (ar < 0) {
				if (br < 0) {
					return 0;
				} else {
					return -1;
				}
			} else {
				if (br < 0) {
					return 1;
				} else {
					int d = ar - br;
					if (d != 0) {
						return d;
					}
				}
			}
		}
	}
}
